import 'dart:typed_data';

import 'package:flutter_chat_ui/pages/onnx/onnx_permission/onnx_permission_tools.dart';

import 'package:logger/logger.dart';
import 'package:record/record.dart';

const int sampleRate = 16000;

///
/// 麦克风录音工具
///
class LLMRecord {
  /// 单例
  static final LLMRecord _instance = LLMRecord._internal();
  LLMRecord._internal();
  // 两种方式使用
  // 1. LLMRecord()
  // 2. LLMRecord.instance
  factory LLMRecord() => _instance;
  static LLMRecord get instance => _instance;

  /// 音频 recorder
  final AudioRecorder audioRecorder = AudioRecorder();
  Stream<Uint8List>? audioStream;

  ///
  /// 初始化录音【由于执行startStream时，即刻处理UI，会卡UI一会儿，所以初始化直接执行startStream，然后再执行pause】
  ///
  /// 已添加权限授权请求
  ///
  /// 返回初始化结果，成功返回空字符串，失败返回错误信息
  ///
  Future<void> initRecord() async {
    try {
      final hasMic = await OnnxPermissionTools.requestMicrophonePermission();
      final hasSpeech = await OnnxPermissionTools.requestSpeechRecognitionPermission();

      if (hasMic && hasSpeech) {
        const recordConfig = RecordConfig(
          encoder: AudioEncoder.pcm16bits,
          sampleRate: sampleRate,
          numChannels: 1,
        );

        // 开始录音并监听，直接暂停处理
        audioRecorder.startStream(recordConfig).then((stream) {
          audioStream = stream;
        }).catchError((e) {
          Logger().e('录音启动失败: $e');
          throw '录音启动失败: $e';
        }).whenComplete(() {
          pauseRecord(); // 立即暂停录音，等待用户操作
        });
      }
    } catch (e) {
      Logger().e('Record 初始化失败: $e');
    }
  }

  ///
  /// 暂停录制
  ///
  Future<void> pauseRecord() async {
    await audioRecorder.pause();
  }

  ///
  /// 恢复录制
  ///
  Future<void> resumeRecord() async {
    await audioRecorder.resume();
  }

  ///
  /// 停止录制
  ///
  Future<String?> stopRecord() async {
    final value = await audioRecorder.stop();
    return value;
  }

  ///
  /// 释放资源
  ///
  Future<void> dispose() async {
    await audioRecorder.dispose();
  }
}
